//package org.jeecg.modules.demo.flowable.service.impl;
//
//import cn.hutool.core.collection.CollectionUtil;
//import cn.hutool.core.util.StrUtil;
//import org.flowable.engine.*;
//import org.flowable.engine.runtime.ProcessInstance;
//import org.flowable.task.api.Task;
//import org.flowable.task.api.TaskQuery;
//import org.flowable.task.api.history.HistoricTaskInstance;
//import org.flowable.task.api.history.HistoricTaskInstanceQuery;
//import org.jeecg.modules.flowable.consts.FlowableDefinitionEnum;
//import org.jeecg.modules.flowable.model.*;
//import org.jeecg.modules.flowable.service.ICommonFlowableProcess;
//import org.jeecg.modules.statements.service.IReportProcessApproveRecordService;
//import org.jeecg.modules.system.util.CommonUtil;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import javax.annotation.Resource;
//import javax.servlet.http.HttpServletResponse;
//import java.util.*;
//import java.util.concurrent.ConcurrentHashMap;
//import java.util.function.Function;
//import java.util.function.Predicate;
//import java.util.stream.Collectors;
//
///**
// * @Author YuXD
// * @Version 1.0
// * @since 2022/4/16
// */
//@Service
//public class CommonFlowableProcessImpl implements ICommonFlowableProcess {
//
//    @Resource
//    private RepositoryService repositoryService;
//    @Resource
//    private RuntimeService runtimeService;
//    @Resource
//    private TaskService taskService;
//    @Resource
//    private HistoryService historyService;
//    @Resource
//    private ProcessEngine processEngine;
//    @Resource
//    private IReportProcessApproveRecordService processApproveRecordService;
//
//    @Autowired
//    ManagementService managementService;
////    @Autowired
////    private IProcessApproveRecordService approveRecordService;
//
//    @Override
//    public boolean checkTaskBelongToAssignee(String taskId, String assignee) {
//        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
//        // 如果任务不存在，默认返回false
//        if (task == null) {
//            return false;
//        }
//        return assignee.equals(task.getAssignee());
//    }
//
//    @Override
//    public ProcessInstanceEntity startProcess(ProcessParam processParam) {
//        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processParam.getProcessDefinitionKey(), processParam.getBusinessKey(), processParam.getVariables());
//        ProcessInstanceEntity instanceEntity = new ProcessInstanceEntity();
//        instanceEntity.setProcessDeploymentId(processInstance.getDeploymentId());
//        instanceEntity.setProcessInstanceId(processInstance.getProcessInstanceId());
//        instanceEntity.setActivityId(processInstance.getActivityId());
//        return instanceEntity;
//    }
//
//    @Override
//    public void handleTask(ProcessParam processParam) {
//        try {
//            /*
//               1、首先查询下是否是自己的，如果不是，则需要拾取下
//                    当前用户和任务的关系：任务处理人(可直接完成任务) or 候选人(需要先拾取，再完成任务)
//             */
//            String assignee = CommonUtil.getLoginUserId();
//            boolean isBelongToAssignee = checkTaskBelongToAssignee(processParam.getTaskId(), assignee);
//            if (!isBelongToAssignee) {
//                taskService.claim(processParam.getTaskId(), assignee);
//            }
//            // 2、完成任务
//            taskService.complete(processParam.getTaskId(), processParam.getVariables());
//            // 3、记录审批结果
//            processApproveRecordService.recordApproveResult(processParam);
//
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//    }
//
//    @Override
//    public List<ProcessStatusEntity> queryProcessStatus(String processInstanceId) {
//        return null;
//    }
//
//    @Override
//    public Map<String, Object> queryProcessVariables(String processInstanceId) {
//        return null;
//    }
//
//    @Override
//    public List<HistanceInstanceEntity> queryHistoryProcess(String assignee) {
//        return null;
//    }
//
//    @Override
//    public void genProcessDiagram(HttpServletResponse httpServletResponse, String processInstanceId) throws Exception {
//
//    }
//
//    @Override
//    public boolean isExistHistoricProcessInstance(String processInstanceId) {
//        return false;
//    }
//
//    @Override
//    public boolean isExistRunningProcessInstance(String processInstanceId) {
//        return false;
//    }
//
//    @Override
//    public void suspendProcessInstance(String processInstanceId) {
//
//    }
//
//    @Override
//    public void activateProcessInstance(String processInstanceId) {
//
//    }
//
//    @Override
//    public void deleteProcessInstance(ProcessParam flowParam) {
//
//    }
//
//    @Override
//    public void rollbackTask(String taskId, String targetTaskKey) {
//
//    }
//
//    @Override
//    public boolean isProcessFinished(String processInstanceId) {
//        return false;
//    }
//
//    @Override
//    public List<TaskInstanceEntity> activeTaskInstance(String assignee, String processInstanceId, FlowableDefinitionEnum flowableType) {
//        List<TaskInstanceEntity> taskInstanceList = CollectionUtil.newArrayList();
//        TaskQuery taskQuery = taskService.createTaskQuery().taskAssignee(assignee).active();
//        if (flowableType != null) {
//            taskQuery.processDefinitionKey(flowableType.getProcessDefinitionKey());
//        }
//        if (StrUtil.isNotEmpty(processInstanceId)) {
//            taskQuery.processInstanceId(processInstanceId);
//        }
//        List<Task> taskList = taskQuery.orderByTaskCreateTime().desc().list();
//        if (CollectionUtil.isNotEmpty(taskList)) {
//            taskList.stream().forEach(task -> {
//                TaskInstanceEntity taskInstance = new TaskInstanceEntity();
//                taskInstance.setId(task.getId());
//                taskInstance.setProcessInstanceId(task.getProcessInstanceId());
//                taskInstance.setName(task.getName());
//                taskInstance.setAssignee(task.getAssignee());
//                taskInstance.setTaskLocalVariables(task.getTaskLocalVariables());
//                taskInstance.setProcessVariables(task.getProcessVariables());
//                taskInstance.setStartTime(task.getCreateTime());
//                taskInstanceList.add(taskInstance);
//            });
//        }
//        return taskInstanceList;
//    }
//
//    @Override
//    public List<TaskInstanceEntity> finishedTaskInstance(String assignee, String processInstanceId, FlowableDefinitionEnum flowableType) {
//        List<TaskInstanceEntity> taskInstanceList = CollectionUtil.newArrayList();
//        // 查询我的已处理的历史
//        HistoricTaskInstanceQuery taskInstanceQuery = historyService.createHistoricTaskInstanceQuery().taskAssignee(assignee).finished();
//        if (flowableType != null) {
//            taskInstanceQuery.processDefinitionKey(flowableType.getProcessDefinitionKey());
//        }
//        if (StrUtil.isNotEmpty(processInstanceId)) {
//            taskInstanceQuery.processInstanceId(processInstanceId);
//        }
//        List<HistoricTaskInstance> historiceTaskInstanceList = taskInstanceQuery.orderByTaskCreateTime().desc().list();
//        if (CollectionUtil.isNotEmpty(historiceTaskInstanceList)) {
//            historiceTaskInstanceList.stream().forEach(task -> {
//                TaskInstanceEntity taskInstance = new TaskInstanceEntity();
//                taskInstance.setId(task.getId());
//                taskInstance.setProcessInstanceId(task.getProcessInstanceId());
//                taskInstance.setName(task.getName());
//                taskInstance.setAssignee(task.getAssignee());
//                taskInstance.setTaskLocalVariables(task.getTaskLocalVariables());
//                taskInstance.setProcessVariables(task.getProcessVariables());
//                taskInstance.setStartTime(task.getCreateTime());
//                taskInstance.setEndTime(task.getEndTime());
//                taskInstanceList.add(taskInstance);
//            });
//        }
//        return taskInstanceList;
//    }
//
//    @Override
//    public TaskInstanceEntity queryTaskById(String taskId) {
//        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
//        TaskInstanceEntity taskInstance = null;
//        if (task != null) {
//            taskInstance = new TaskInstanceEntity();
//            taskInstance.setId(task.getId());
//            taskInstance.setProcessInstanceId(task.getProcessInstanceId());
//            taskInstance.setName(task.getName());
//            taskInstance.setAssignee(task.getAssignee());
//            taskInstance.setTaskLocalVariables(task.getTaskLocalVariables());
//            taskInstance.setProcessVariables(task.getProcessVariables());
//        }
//        return taskInstance;
//    }
//
//    @Override
//    public List<TaskInstanceEntity> queryTaskByProcessInstanceId(String processInstanceId, String assignee, String taskType) {
//        List<TaskInstanceEntity> taskInstanceList = CollectionUtil.newArrayList();
//        if (!"CURRENT".equals(taskType)) {
//            // 当前流程实例历史任务查询
//            HistoricTaskInstanceQuery historicTaskInstanceQuery = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId);
//            if (StrUtil.isNotEmpty(assignee)) {
//                historicTaskInstanceQuery.taskAssignee(assignee);
//            }
//            List<HistoricTaskInstance> historicTaskList = historicTaskInstanceQuery.orderByHistoricTaskInstanceStartTime().asc().list();
//            if (CollectionUtil.isNotEmpty(historicTaskList)) {
//                historicTaskList.stream().forEach(historicTask -> {
//                    TaskInstanceEntity taskInstance = new TaskInstanceEntity();
//                    taskInstance.setId(historicTask.getId());
//                    taskInstance.setName(historicTask.getName());
//                    taskInstance.setAssignee(historicTask.getAssignee());
//                    taskInstance.setStartTime(historicTask.getStartTime());
//                    taskInstance.setEndTime(historicTask.getEndTime());
//                    taskInstance.setTaskDefinitionKey(historicTask.getTaskDefinitionKey());
//                    taskInstanceList.add(taskInstance);
//                });
//            }
//        }
//        if (!"HISTORY".equals(taskType)) {
//            // 当前执行中任务查询
//            TaskQuery taskQuery = taskService.createTaskQuery().processInstanceId(processInstanceId);
//            if (StrUtil.isNotEmpty(assignee)) {
//                taskQuery.taskCandidateOrAssigned(assignee);
//            }
//            List<Task> taskList = taskQuery.orderByTaskCreateTime().asc().list();
//            if (CollectionUtil.isNotEmpty(taskList)) {
//                taskList.stream().forEach(task -> {
//                    TaskInstanceEntity taskInstance = new TaskInstanceEntity();
//                    taskInstance.setId(task.getId());
//                    taskInstance.setName(task.getName());
//                    taskInstance.setAssignee(task.getAssignee());
//                    taskInstance.setStartTime(task.getCreateTime());
//                    taskInstance.setTaskDefinitionKey(task.getTaskDefinitionKey());
//                    taskInstanceList.add(taskInstance);
//                });
//            }
//        }
//        // 去重并按照开始时间升序排序
//        return taskInstanceList.stream().filter(distinctByKey(TaskInstanceEntity::getId)).sorted(Comparator.comparing(TaskInstanceEntity::getStartTime)).collect(Collectors.toList());
//    }
//
//    private <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
//        Set<Object> seen = ConcurrentHashMap.newKeySet();
//        return t -> seen.add(keyExtractor.apply(t));
//    }
//
//    //    @Override
////    public List<ProcessStatusEntity> queryProcessStatus(String processInstanceId) {
////        List<ProcessStatusEntity> result = new ArrayList<>();
////        List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery()
////                .processInstanceId(processInstanceId).list();
////        if (CollectionUtils.isEmpty(historicTaskInstances)) {
////            throw new RuntimeException("Process instance [" + processInstanceId + "] not exist");
////        }
////        for (HistoricTaskInstance hti : historicTaskInstances) {
////            String taskId = hti.getId();
////            String taskName = hti.getName();
////            String assignee = hti.getAssignee();
////            Date createTime = hti.getCreateTime();
////            String comment = null;
////            String approved = null;
////            List<Comment> comments = taskService.getTaskComments(taskId);
////            if (!CollectionUtils.isEmpty(comments)) {
////                comment = comments.get(0).getFullMessage();
////                if (null != comment) {
////                    //这里进行评论的JSON数据的逆操作提取数据
////                    ObjectMapper mapper = new ObjectMapper();
////                    try {
////                        Map<String, Object> data = mapper.readValue(comment, Map.class);
////                        approved = data.get("approved").toString();
////                        comment = data.get("comment").toString();
////                    } catch (Exception e) {
////                        System.out.println(e.toString());
////                    }
////                }
////            }
////            ProcessStatusEntity pd = new ProcessStatusEntity();
////            pd.setTaskName(taskName);
////            pd.setAssignee(assignee);
////            pd.setCreateTime(createTime);
////            pd.setApproved(approved);
////            pd.setComment(comment);
////            pd.setTaskId(hti.getId());
////            pd.setProcessInstanceId(hti.getProcessInstanceId());
////            result.add(pd);
////        }
////        return result;
////    }
////
////    @Override
////    public Map<String, Object> queryProcessVariables(String processInstanceId) {
////        List<HistoricVariableInstance> historicVariableInstances =
////                historyService.createHistoricVariableInstanceQuery()
////                        .processInstanceId(processInstanceId).list();
////        if (historicVariableInstances == null) {
////            throw new RuntimeException("Process instance [" + processInstanceId + "] not exist");
////        }
////        Map<String, Object> ret = new HashMap<>();
////        for (HistoricVariableInstance var : historicVariableInstances) {
////            ret.put(var.getVariableName(), var.getValue());
////        }
////        return ret;
////    }
////
////    @Override
////    public List<HistanceInstanceEntity> queryHistoryProcess(String assignee) {
////        List<HistanceInstanceEntity> result = new ArrayList<>();
////        List<HistoricActivityInstance> activities = historyService.createHistoricActivityInstanceQuery()
////                .taskAssignee(assignee).finished().orderByHistoricActivityInstanceEndTime().desc().list();
////        for (HistoricActivityInstance h : activities) {
////            HistanceInstanceEntity d = new HistanceInstanceEntity();
////            d.setProcessInstanceId(h.getProcessInstanceId());
////            d.setTaskId(h.getTaskId());
////            d.setStartTime(h.getStartTime());
////            d.setEndTime(h.getEndTime());
////            result.add(d);
////        }
////        return result;
////    }
////
////    @Override
////    public void genProcessDiagram(HttpServletResponse httpServletResponse,
////                                  String processInstanceId) throws Exception {
////        ProcessInstance pi = runtimeService.createProcessInstanceQuery().
////                processInstanceId(processInstanceId).singleResult();
////        //流程走完的不显示图
////        if (pi == null) {
//////            System.out.println("不存在该流程或则流程已经走完");
////            throw new RuntimeException("不存在该流程或则流程已经走完");
//////            return;
////        }
////        Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
////        //使用流程实例ID，查询正在执行的执行对象表，返回流程实例对象
////        String InstanceId = task.getProcessInstanceId();
////        List<Execution> executions = runtimeService
////                .createExecutionQuery()
////                .processInstanceId(InstanceId)
////                .list();
////        //得到正在执行的Activity的Id
////        List<String> activityIds = new ArrayList<>();
////        List<String> flows = new ArrayList<>();
////        for (Execution exe : executions) {
////            List<String> ids = runtimeService.getActiveActivityIds(exe.getId());
////            activityIds.addAll(ids);
////        }
////        //获取流程图
////        BpmnModel bpmnModel = repositoryService.getBpmnModel(pi.getProcessDefinitionId());
////        ProcessEngineConfiguration engineConf = processEngine.getProcessEngineConfiguration();
////        ProcessDiagramGenerator diagramGenerator = engineConf.getProcessDiagramGenerator();
////        InputStream in = diagramGenerator.generateDiagram(bpmnModel,
////                "png",
////                activityIds,
////                flows,
////                engineConf.getActivityFontName(),
////                engineConf.getLabelFontName(),
////                engineConf.getAnnotationFontName(),
////                engineConf.getClassLoader(),
////                1.0, true);
////        OutputStream out = null;
////        byte[] buf = new byte[1024];
////        int length = 0;
////        try {
////            out = httpServletResponse.getOutputStream();
////            while ((length = in.read(buf)) != -1) {
////                out.write(buf, 0, length);
////            }
////        } finally {
////            if (in != null) {
////                in.close();
////            }
////            if (out != null) {
////                out.close();
////            }
////        }
////    }
////
////    @Override
////    public boolean isExistHistoricProcessInstance(String processInstanceId) {
////        HistoricProcessInstance historicProcessInstance =
////                historyService.createHistoricProcessInstanceQuery().
////                        processInstanceId(processInstanceId).singleResult();
////        if (historicProcessInstance == null) {
////            return false;
////        }
////        return true;
////    }
////
////    @Override
////    public boolean isExistRunningProcessInstance(String processInstanceId) {
////        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().
////                processInstanceId(processInstanceId).singleResult();
////        if (processInstance == null) {
////            return false;
////        }
////        return true;
////    }
////
////    @Override
////    public void suspendProcessInstance(String processInstanceId) {
////        runtimeService.suspendProcessInstanceById(processInstanceId);
////    }
//
//    @Override
//    public void terminateProcessInstance(ProcessParam paramObj) {
//        runtimeService.deleteProcessInstance(paramObj.getProcessInstanceId(), paramObj.getRemark());
//    }
//
////    @Override
////    public void activateProcessInstance(String processInstanceId) {
////        runtimeService.activateProcessInstanceById(processInstanceId);
////    }
//
//    //@Override
//    //public void deleteProcessInstance(ProcessParam paramObj) {
//    //    //查询是否操作
//    //    long count = runtimeService.createExecutionQuery().processInstanceId(paramObj.getProcessInstanceId()).count();
//    //    if (count > 0) {
//    //
//    //        DeleteFlowableProcessInstanceCmd cmd =
//    //                new DeleteFlowableProcessInstanceCmd(paramObj.getProcessInstanceId(),
//    //                        paramObj.getDeleteReason(), true);
//    //        managementService.executeCommand(cmd);
//    //        //runtimeService.deleteProcessInstance(processInstanceId,deleteReason);
//    //    } else {
//    //        //删除历史数据的流程实体
//    //        historyService.deleteHistoricProcessInstance(paramObj.getProcessInstanceId());
//    //    }
//    //}
//
////    @Override
////    public void rollbackTask(String taskId, String targetTaskKey) {
////        Task currentTask = taskService.createTaskQuery().taskId(taskId).singleResult();
////        if (currentTask == null) {
////            return;
////        }
////        List<String> key = new ArrayList<>();
////        key.add(currentTask.getTaskDefinitionKey());
////        runtimeService.createChangeActivityStateBuilder()
////                .processInstanceId(currentTask.getProcessInstanceId())
////                .moveActivityIdsToSingleActivityId(key, targetTaskKey)
////                .changeState();
////    }
////
////    @Override
////    public boolean isProcessFinished(String processInstanceId) {
////        return historyService.createHistoricProcessInstanceQuery().finished()
////                .processInstanceId(processInstanceId).count() > 0;
////    }
//}
